package com.zhugang.week13.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program algorithms
 * @description: findBottomLeftValue
 * @author: chanzhugang
 * @create: 2022/12/28 19:19
 */
public class FindBottomLeftValue {

    /**
     * 513 找树左下角的值
     * https://leetcode.cn/problems/find-bottom-left-tree-value/
     *
     * @param root
     * @return
     */
    public int findBottomLeftValue(TreeNode root) {
        /**
         * 层序遍历，从右往左
         */
        int result = -1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            result = node.val;
            if (node.right != null) {
                queue.add(node.right);
            }
            if (node.left != null) {
                // 队列中出来的最后一个树是左下脚的数
                queue.add(node.left);
            }
        }
        return result;
    }

    public int findBottomLeftValue2(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // 更新节点
            root = queue.poll();
            if (root.right != null) queue.offer(root.right);
            if (root.left != null) queue.offer(root.left);
        }
        return root.val;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}